package com.cjhme.web.action.fileupload;



import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cjhme.common.constant.SystemBusniessMarkConstants;
import com.cjhme.common.annotation.Auth;
import com.cjhme.common.constant.CommonConstants;
import com.cjhme.common.constant.DataDicConstants;
import com.cjhme.common.constant.DataDicItemConstants;
import com.cjhme.common.model.base.ResultData;
import com.cjhme.common.model.datadic.DataDicItemBean;
import com.cjhme.common.model.fileupload.FileDataBean;
import com.cjhme.common.model.user.UserBean;
import com.cjhme.common.util.ReadFileUtil;
import com.cjhme.common.util.UUIDUtil;
import com.cjhme.common.util.UploadImgUtil;
import com.cjhme.system.impl.service.fileupload.FileDataService;
import com.cjhme.web.base.action.SysBaseAction;

/**
 * 
 * <p>
 * Title: FileUploadAction.java
 * </p>
 * Description: 文件上传
 * <p>
 * Modify histoty:
 * 
 * @author cjh
 * @version 1.0
 */
@Controller
@Scope("prototype")
@RequestMapping("/fileUpload")
public class FileUploadAction extends SysBaseAction {

	Log LOGGER = LogFactory.getLog(FileUploadAction.class);


	private FileDataService fileDataService;
	
	/**
	 * 图片上传
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/uploadImg",method=RequestMethod.POST)
	public void uploadImg(HttpSession session,HttpServletRequest request,HttpServletResponse response){
		this.upload(session, request, response, "imgUpload", "图片",SystemBusniessMarkConstants.SYS_UPLOAD_IMG);
	}
	
	/**
	 * 文件上传
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
	public void uploadFile(HttpSession session,HttpServletRequest request,HttpServletResponse response){
		this.upload(session, request, response, "fileUpload", "文件",SystemBusniessMarkConstants.SYS_UPLOAD_FILE);
	}
	
	
	/**
	 * 预览图片
	 * 
	 * @param session
	 * @param request
	 * @param response
	 */
	@Auth(verifyToken=false)
	@RequestMapping(value = "/previewImg", method = { RequestMethod.POST, RequestMethod.GET })
	public void previewImg(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		this.fileRead(session, request, response, "图片", SystemBusniessMarkConstants.SYS_UPLOAD_IMG);
	}
	
	/**
	 * 下载文件
	 * 
	 * @param session
	 * @param request
	 * @param response
	 */
	@Auth(verifyToken=false)
	@RequestMapping(value = "/downloadFile", method = { RequestMethod.POST, RequestMethod.GET })
	public void downloadFile(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		this.fileRead(session, request, response, "文件", SystemBusniessMarkConstants.SYS_UPLOAD_FILE);
	}
	
	/**
	 * 文件读取
	 * @param session
	 * @param request
	 * @param response
	 * @param label
	 * @param busniessMark
	 */
	private void fileRead(HttpSession session, HttpServletRequest request, HttpServletResponse response,String label,String busniessMark) {
		try {
			String busniessId = String.valueOf(request.getParameter("busniessId"));
			UserBean userBean = (UserBean) session.getAttribute(CommonConstants.MANAGE_USER_SESSION);
			if (!StringUtils.isEmpty(userBean) && !StringUtils.isEmpty(busniessId)) {
				Map<String, Object> parameter = new HashMap<String, Object>();
				parameter.put("busniessId", busniessId);
				parameter.put("busniessMark", busniessMark);
				FileDataBean fileDataBean = this.fileDataService.queryOneFileDataByBMarkAndBId(parameter);
				if (!StringUtils.isEmpty(fileDataBean)) {
					ReadFileUtil.readFileToResponse(response, fileDataBean.getFileUrl(), fileDataBean.getFileName(),label);
				}else{
					LOGGER.error(label+"读取未成功");
				}
				
			}else{
				LOGGER.error(label+"读取未成功");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(label+"读取失败,错误——>" + e);
		}
	}
	
	/**
	 * 文件上传
	 * @param session
	 * @param request
	 * @param response
	 * @param formFileName
	 * @param label
	 * @param busniessMark
	 */
	private void upload(HttpSession session,HttpServletRequest request,HttpServletResponse response,String formFileName,String label,String busniessMark) {
		ResultData resultData=new ResultData();
		try{
			String busniessId = request.getParameter("busniessId");
			
			UserBean userBean = (UserBean) session.getAttribute(CommonConstants.MANAGE_USER_SESSION);
			DataDicItemBean dataDicItemBean=this.getDataDicItemByDicTypeCodeAndItemCode(DataDicConstants.SYS_FILE_UPLOAD_PATH, DataDicItemConstants.SYS_IMG_PATH);
			
			if (!StringUtils.isEmpty(userBean) && !StringUtils.isEmpty(dataDicItemBean) ) {
				LOGGER.info(label+"保存地址——>"+dataDicItemBean.getDicItemValue());
				
				FileDataBean fileDataBean = UploadImgUtil.upload(request, formFileName, dataDicItemBean.getDicItemValue(),true);
				if(null!=fileDataBean && !StringUtils.isEmpty(fileDataBean.getFileUrl())) {
					
					Map<String, Object> fileDataParameter = new HashMap<String, Object>();
					fileDataParameter.put("busniessMark",busniessMark);
					fileDataParameter.put("busniessId", busniessId);
					fileDataParameter.put("fileUrl", fileDataBean.getFileUrl());
					fileDataParameter.put("fileName", fileDataBean.getFileName());
					fileDataParameter.put("fileDescript", label+"上传！");
					fileDataParameter.put("createUserId", userBean.getUserId());
					fileDataParameter.put("fileId", UUIDUtil.createUUID32());
					
					this.fileDataService.saveFileData(fileDataParameter);
					
					resultData.setResultType(CommonConstants.RESULT_SUCCESS);
					resultData.setResultMsg(label+"上传成功！");
					resultData.setResultData(fileDataParameter);

					LOGGER.info(label+"上传成功！");
				}else {
					resultData.setResultType(CommonConstants.RESULT_FAILURE);
					resultData.setResultMsg(label+"上传未成功！");
				
					LOGGER.info(label+"上传未成功！");
				}
				
			}else {
				resultData.setResultType(CommonConstants.RESULT_FAILURE);
				resultData.setResultMsg(label+"上传未成功！");
			
				LOGGER.info(label+"上传未成功！");
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			resultData.setResultType(CommonConstants.RESULT_ERROR);
			resultData.setResultMsg(label+"上传失败！");
			LOGGER.error(label+"上传失败,错误——>"+e);
		}
		resultData.printJsonData(response,"text/html;charset=utf-8");
	}

	
	public FileDataService getFileDataService() {
		return fileDataService;
	}

	@Resource(name="system.fileDataService")
	public void setFileDataService(FileDataService fileDataService) {
		this.fileDataService = fileDataService;
	}

}
